#include "stdafx.h"
#include <cassert>
#include "MyControls/Player.h"
#include "MyControls/Sequence.h"

namespace My {

Player::Player() : m_PlayMode(PlayStop), m_Loop(true) 
{ 
	ReadSettings();
}

Player::~Player()
{ 
	WriteSettings();
}

void Player::TimeStep()
{
	Sequence * Seq = GetSequence();
	assert(Seq);
	assert(!Seq->IsEmpty());
	if (!IsPlaying())
		return;

	bool ChangeDirection;
	int n = NextFrame(&ChangeDirection);
	if (ChangeDirection)
		m_PlayMode = m_PlayMode == PlayForward ? PlayBackward : PlayForward;
	Seq->SetPreviewFrame(n);
}

int Player::NextFrame(bool * ChangeDirection) const
{
	Sequence * Seq = GetSequence();
	assert(Seq);
	assert(!Seq->IsEmpty());
	if (ChangeDirection)
		*ChangeDirection = false;
	int t = Seq->GetPreviewFrame();
	if (!IsPlaying())
		return t;

	Span s = Seq->GetWorkArea();
	if (m_PlayMode == PlayForward) {
		if (++t >= s.last) {
			if (!m_Loop && t == s.last) {
				t = s.last - 2;
				if (ChangeDirection)
					*ChangeDirection = true;
			} else
				t = s.first;
		}
		return t;
	}
	else {
		if (--t < s.first) {
			if (!m_Loop && t == s.first - 1) {
				t = s.first + 1;
				if (ChangeDirection)
					*ChangeDirection = true;
			} else
				t = s.last - 1;
		}
		return t;
	}
}

void Player::SetPlayMode(PlayMode m)
{
	if (m_PlayMode == m)
		return;

	if (m_PlayMode == PlayFollow) {
		OnDeactivateFollow();
		GetSequence()->SetPreviewFrame(GetSequence()->GetCurrentFrame());
	}
	else if (m == PlayStop) {
		m_PlayMode = m;
		GetSequence()->SetCurrentFrame(GetSequence()->GetPreviewFrame());
	}
	m_PlayMode = m;
	if (m_PlayMode == PlayFollow)
		OnActivateFollow();

	if (IsPlaying())
		StartTimer();
	else {
		StopTimer();
	}

	DispatchEvent(PlaymodeChange(* this));
}

void Player::WriteSettings()
{
	AfxGetApp()->WriteProfileInt("Time", "Loop", GetLoop() ? 1 : 0);
	AfxGetApp()->WriteProfileInt("Time", "AutoFollow", GetAutoFollow() ? 1 : 0);
}

void Player::ReadSettings()
{
	SetLoop(AfxGetApp()->GetProfileInt("Time", "Loop", 1) != 0);
	SetAutoFollow(AfxGetApp()->GetProfileInt("Time", "AutoFollow", 1) != 0);
}

} //namespace My
